package com.csw.android.dev_utils.liveData

import androidx.lifecycle.MutableLiveData

/**
 * 代理LiveData，当有外部订阅者时，订阅[outerLiveData]，当所有外部订阅者都移除时，取消[outerLiveData]订阅
 */
class ProxyLiveData<T> : ObserverChangeLiveData<T> {
    private val workLiveDataObserver = CommonLiveDataListener<T> {
        super.setValue(it)
    }
    var outerLiveData: MutableLiveData<T?>? = null
        set(value) {
            if (field != value) {
                field = value
//                LogUtils.d(this@ProxyLiveData, "$name setOuterLiveData(${field.hashCode()})")
                workLiveDataObserver.liveData = if (hasObservers()) field else null
            }
        }
    private var name: String? = null

    constructor() : super()

    constructor(name: String) : super() {
        this.name = name
    }

    constructor(value: T?) : super(value)

    init {
        onObserverChanged = {
            if (it) {
//                LogUtils.d(this@ProxyLiveData, "$name startListener(${outerLiveData.hashCode()})")
                workLiveDataObserver.liveData = outerLiveData
            } else {
//                LogUtils.d(this@ProxyLiveData, "$name stopListener(${outerLiveData.hashCode()})")
                workLiveDataObserver.liveData = null
            }
        }
    }

    override fun postValue(value: T) {
        val finalOuterLiveData = workLiveDataObserver.liveData
        if (finalOuterLiveData is MutableLiveData) {
            finalOuterLiveData.postValue(value)
        } else {
            super.postValue(value)
        }
    }

    override fun setValue(value: T?) {
        val finalOuterLiveData = workLiveDataObserver.liveData
        if (finalOuterLiveData is MutableLiveData) {
            finalOuterLiveData.value = value
        } else {
            super.setValue(value)
        }
    }

}